import cv2
import os.path
import numpy as np
from imageDeal import compareImage, showImage, imageSharpen, saveImage


def test(image):
    diff = compareImage(image)
    diff.maxGray()
    # diff.createrGrayImg()
    diff.createWhite()
    diff.imgDiff(diff.whiteImg)

    imgSharpen = imageSharpen(diff.diffImg)
    imgSharpen.sobel()
    return imgSharpen.image
    # showImage(diff.srcImg)
    # showImage(diff.whiteImg)
    # showImage(diff.diffImg)
    # showImage(imgSharpen.image)


def warpAffineTest(image):
    mean = 0
    variance = 0.01
    gaussian_noise = np.random.normal(mean, variance ** 0.7, image.shape)
    noisy_image = cv2.add(image.astype(np.float64), gaussian_noise)

    # 定义变换矩阵
    M = np.array([[1, 0, 0],
                  [0, 1, 0]], dtype=np.float32)
    # 进行维纳滤波
    filtered_image = cv2.warpAffine(noisy_image, M, image.shape[::-1])
    filtered_image = cv2.normalize(filtered_image, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
    return filtered_image


def deconvolution(image):
    # 读取退化图像和点扩散函数（PSF）
    psf = cv2.imread('psf.jpg', cv2.IMREAD_GRAYSCALE)
    # 进行盲去卷积
    restored_image, _ = cv2.deconvolution(image.astype(np.float64), psf.astype(np.float64))

    # 将图像归一化到[0, 255]范围内
    restored_image = cv2.normalize(restored_image, None, 0, 255, cv2.NORM_MINMAX).astype(np.uint8)
    return restored_image




# 自定义模糊
def custom_blur_demo(image):
    kernel = np.array(([[0, -1, 0], [-1, 6, -1], [0, -1, 0]]), np.float32)
    # 中间的像素比重为5 其他和为0和-1 总权重为1，算子自定义取值。总和为0：做边缘梯度。总和为1：做锐化增强
    dst = cv2.filter2D(image, -1, kernel=kernel)
    cv2.imshow("custom_blur_demo", dst)

# src = cv2.imread("C:/Users/1234/Desktop/yolotestdata/23.05.26/circlesring/50.bmp", 0)  #读取图片位置
# cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
# cv2.imshow("input image", src)
# custom_blur_demo(src)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


if __name__ == '__main__':
    # basePath = "C:/Users/1234/Desktop/yolotestdata/markyangben/ring/ganyatu/4/"
    basePath = "C:/Users/1234/Desktop/yolotestdata/markyangben/ring/2.0/B/"
    savePath = os.path.join(basePath, "warpAffine/")
    if not os.path.exists(savePath):
        os.makedirs(savePath)

    for i in range(1, 41):
        crname = str(i) + ".bmp"
        imgPath = os.path.join(basePath, crname)
        saveImgP = os.path.join(savePath, crname)
        srcimg = cv2.imread(imgPath, 0)
        sobel = imageSharpen(srcimg)
        sobel.lapulasi()
        print(i)
        resImg = warpAffineTest(sobel.image)
        saveImage(saveImgP, resImg)